package com.carbon.controller;

import java.util.ArrayList;
import java.util.List;
import java.util.Arrays;
import java.util.stream.Collectors;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.carbon.common.core.text.Convert;
import com.carbon.domain.Batch;
import com.carbon.dto.ProductDto;
import com.carbon.dto.ProductNodeTree;
import com.carbon.service.BatchService;
import com.carbon.utils.QiniuUtils;
import com.carbon.vo.SearchParams;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.RequiredArgsConstructor;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.carbon.common.annotation.Log;
import com.carbon.common.core.controller.BaseController;
import com.carbon.common.core.domain.AjaxResult;
import com.carbon.common.enums.BusinessType;
import com.carbon.domain.Product;
import com.carbon.service.IProductService;
import com.carbon.common.utils.poi.ExcelUtil;

import javax.annotation.Resource;

/**
 * 生产单位Controller
 *
 * @author wfk
 * @date 2023-08-22
 */
@RestController
@RequestMapping("/wms/product")
@Api(value = "生产单位控制器", tags = {"生产单位管理"})
@RequiredArgsConstructor(onConstructor_ = @Autowired)
public class ProductController extends BaseController {
    @Resource
    private IProductService productService;
    @Resource
    private BatchService batchService;
    @Resource
    private QiniuUtils qiniuUtils;

    /**
     * 获取生产沧桑 树形结构
     * @return
     */
    @GetMapping("/getProductTreeNode")
    public AjaxResult getProductTreeNode(){
        LambdaUpdateWrapper<Product> lqw = new LambdaUpdateWrapper<Product>()
                .eq(Product::getStatus, "0");
        List<Product> list = productService.list(lqw);
        ArrayList<ProductNodeTree> trees = new ArrayList<>();
        list.stream().forEach(item->{
            ArrayList<ProductNodeTree> tree1 = new ArrayList<>();
            ProductNodeTree productNodeTree = new ProductNodeTree();
            LambdaUpdateWrapper<Batch> lqw1 = new LambdaUpdateWrapper<Batch>().eq(Batch::getProductId, item.getId());
            List<Batch> list1 = batchService.list(lqw1);
            productNodeTree.setId(item.getId());
            productNodeTree.setName(item.getProductName());
            if (!list.isEmpty()){
                list1.stream().forEach(item1->{
                    ProductNodeTree productNodeTree1 = new ProductNodeTree();
                    productNodeTree1.setId(Convert.toLong(item1.getId()));
                    productNodeTree1.setName(item1.getBatchId());
                    tree1.add(productNodeTree1);
                });
            }
            productNodeTree.setChildren(tree1);
            trees.add(productNodeTree);
        });
        return success(trees);
    }
    /**
     * 获取全部生产商
     * @return
     */
    @GetMapping("/getProductInfoList")
    public AjaxResult getProductInfoList() {
        LambdaUpdateWrapper<Product> lqw = new LambdaUpdateWrapper<Product>()
                .eq(Product::getStatus, "0");
        return success(productService.list(lqw));
    }

    /**
     * 修改生产单位状态
     *
     * @param id
     * @param status
     * @return
     */
    @GetMapping("/changeProductStatus")
    public AjaxResult changeProductStatus(Long id, String status) {
        Product product = new Product();
        product.setId(id);
        product.setStatus(status);
        return productService.updateById(product) ? success() : error();
    }

    /**
     * 查询生产单位列表
     */
    @ApiOperation("查询生产单位列表")
    @GetMapping("/list")
    public AjaxResult list(SearchParams params) {
        Page<Product> productPage = new Page<>(params.getPageNum(), params.getPageSize());
        LambdaUpdateWrapper<Product> lqw = new LambdaUpdateWrapper<Product>()
                .like(ObjectUtil.isNotEmpty(params.getSearch()), Product::getProductName, params.getSearch())
                .orderByAsc(Product::getSort)
                .orderByAsc(Product::getCreateTime);
        productPage = productService.page(productPage, lqw);
        List<Product> records = productPage.getRecords();
        if (ObjectUtil.isEmpty(records)) {
            return success();
        }
        return success()
                .put("rows", records)
                .put("total", productPage.getTotal());
    }

    /**
     * 导出生产单位列表
     */
    @ApiOperation("导出生产单位列表")
    @Log(title = "生产单位", businessType = BusinessType.EXPORT)
    @GetMapping("/export")
    public AjaxResult export(Product product) {
        List<Product> list = productService.list(new QueryWrapper<Product>(product));
        ExcelUtil<Product> util = new ExcelUtil<Product>(Product.class);
        return util.exportExcel(list, "生产单位数据");
    }

    /**
     * 获取生产单位详细信息
     */
    @ApiOperation("获取生产单位详细信息")
    @GetMapping(value = "/{id}")
    public AjaxResult getInfo(@PathVariable("id") Long id) {
        LambdaUpdateWrapper<Batch> lqw = new LambdaUpdateWrapper<Batch>()
                .eq(Batch::getProductId, id);
        ProductDto productDto = new ProductDto();
        BeanUtil.copyProperties(productService.getById(id), productDto);
        productDto.setBatchList(batchService.list(lqw));
        return AjaxResult.success(productDto);
    }

    /**
     * 新增生产单位
     */
    @ApiOperation("新增生产单位")
    @Log(title = "生产单位", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody ProductDto product) {
        if (ObjectUtil.isEmpty(product.getProductName())) {
            return AjaxResult.error("生产单位为空");
        }
        if (ObjectUtil.isEmpty(product.getImg())) {
            return AjaxResult.error("图片为空");
        }
        if (ObjectUtil.isNotEmpty(product.getId())) {
            return edit(product);
        }
        LambdaUpdateWrapper<Product> lqw = new LambdaUpdateWrapper<Product>()
                .eq(Product::getProductName, product.getProductName());
        if (ObjectUtil.isNotEmpty(productService.list(lqw))) {
            return AjaxResult.error("生产单位:" + product.getProductName() + "重复");
        }
        productService.save(product);
        List<Batch> batchList = product.getBatchList();
        if (ObjectUtil.isNotEmpty(batchList)) {
            List<String> collect = batchList.stream().map(Batch::getBatchId).collect(Collectors.toList());
            LambdaUpdateWrapper<Batch> lqw1 = new LambdaUpdateWrapper<Batch>()
                    .in(Batch::getBatchId, collect);
            List<Batch> list = batchService.list(lqw1);
            if (ObjectUtil.isNotEmpty(list)) {
                return AjaxResult.error("生产批号重复");
            }
            batchList.stream().forEach(item1 -> {
                String batchId = item1.getBatchId();
                if (ObjectUtil.isEmpty(batchId)) {
                    batchId = DateUtil.now();
                }
                item1.setProductId(Convert.toInt(product.getId()));
                item1.setBatchId(StrUtil.addSuffixIfNot(StrUtil.addPrefixIfNot(batchId, "【"), "】"));
            });
            batchService.saveBatch(batchList);
        }
        return success();
    }

    /**
     * 修改生产单位
     */
    @ApiOperation("修改生产单位")
    @Log(title = "生产单位", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody ProductDto product) {
        Product byId = productService.getById(product.getId());
        String img = product.getImg();
        String img1 = byId.getImg();
        // 删除七牛云
        if (!img.equals(img1)) {
            if (img1!=null){
                qiniuUtils.deleteFileFromQiniu(img1.substring(img1.lastIndexOf("/")).split("/")[1]);
            }
        }
        if (!byId.getProductName().equalsIgnoreCase(product.getProductName())) {
            LambdaUpdateWrapper<Product> lqw = new LambdaUpdateWrapper<Product>()
                    .eq(Product::getProductName, product.getProductName());
            if (ObjectUtil.isNotEmpty(productService.list(lqw))) {
                return AjaxResult.error("生产单位:" + product.getProductName() + "重复");
            }
        }
        List<Batch> batchList = product.getBatchList();
        if (ObjectUtil.isNotEmpty(batchList)) {

            List<String> collect = batchList.stream().filter(item->{
                if (ObjectUtil.isNotEmpty(item.getId())){
                    return false;
                }
                return true;
            }).map(Batch::getBatchId).distinct().collect(Collectors.toList());
            if (ObjectUtil.isNotEmpty(collect)){
                LambdaUpdateWrapper<Batch> lqw1 = new LambdaUpdateWrapper<Batch>()
                        .in(Batch::getBatchId, collect);
                List<Batch> list = batchService.list(lqw1);
                if (ObjectUtil.isNotEmpty(list)) {
                    return AjaxResult.error("生产批号重复");
                }
            }



            batchList.stream().forEach(item1 -> {
                String batchId = item1.getBatchId();
                if (ObjectUtil.isEmpty(batchId)) {
                    batchId = DateUtil.now();
                }
                item1.setBatchId(StrUtil.addSuffixIfNot(StrUtil.addPrefixIfNot(batchId, "【"), "】"));

                if (ObjectUtil.isEmpty(item1.getId())) {
                    item1.setProductId(Convert.toInt(product.getId()));
                    batchService.save(item1);
                }else {
                    batchService.updateById(item1);
                }
            });
        }
        return toAjax(productService.updateById(product));
    }

    /**
     * 删除生产单位
     */
    @ApiOperation("删除生产单位")
    @Log(title = "生产单位", businessType = BusinessType.DELETE)
    @DeleteMapping("/{ids}")
    public AjaxResult remove(@PathVariable Long[] ids) {
        LambdaUpdateWrapper<Batch> lqw = new LambdaUpdateWrapper<Batch>()
                .in(Batch::getProductId, ids);
        batchService.remove(lqw);
        // 删除七牛云
        productService.listByIds(Arrays.asList(ids)).stream().map(Product::getImg).distinct().filter(item->{
            if (ObjectUtil.isEmpty(item)){
                return false;
            }
            return true;
        }).forEach(item->{
            List<String> split = StrUtil.split(item, "/");
            qiniuUtils.deleteFileFromQiniu(split.get(split.size()-1));
        });
        return toAjax(productService.removeByIds(Arrays.asList(ids)));
    }
}
